﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.SqlClient;
using DevExpress.Web.ASPxTreeList;
using DevExpress.Web.ASPxClasses;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxPanel;
using System.Text.RegularExpressions;
using DAL;


public partial class EditCommunity : System.Web.UI.Page
{
    static string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["CMSConnectionString"].ToString();
    static string ParentID="0";
    protected void Page_Load(object sender, EventArgs e)
    {

        if (Session["username"] == null)
        {
            Response.Redirect("Login.aspx");
        }
        string username = CMSUser.Current.Name;
        if (!username.Equals("Administrator"))
        {
            this.DXTreelist.SettingsText.CommandDelete = "";
        }
        tvShow();
        //this.lblcity.Text = Session["city"].ToString();
        
    }

    // 将数据绑定到treeview中
    private void tvShow()
    {
        DataTable dt = Frame.Global.GlobalSqlHelper.ExecuteSQLToDataTable("select * from Community order by Community_ID");
        this.DXTreelist.DataSource = dt;
        this.DXTreelist.DataBind();  
    }

    #region 修改节点
    //修改节点
    protected void DXTreelist_NodeUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
        string NewCommunityID = e.NewValues[0].ToString();
        string NewCommunityName = e.NewValues[1].ToString();
        try
        {
            //修改数据

            string strSql = "update Community set Community_Name='" + NewCommunityName + "'where Community_ID='" + NewCommunityID + "'";
            int count = Convert.ToInt32(Frame.Global.GlobalSqlHelper.ExecuteSQL(strSql));
            if (count > 0)
            { 
              Frame.Global.GlobalFunctions.Alert("修改成功！");
            }
        }
        catch (Exception)
        {

            throw;
        }
        tvShow();
        DXTreelist.CancelEdit();
        e.Cancel = true;
    }
    #endregion 

    #region 删除节点
    //删除节点
    protected void DXTreelist_NodeDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
        string v = e.Values.ToString();
        string CommunityID = e.Keys[0].ToString();     //获取删除指定的社区编号
        string strSql = "delete from Community where Community_ID='" + CommunityID + "'";
        try
        {
            int count = Convert.ToInt32(Frame.Global.GlobalSqlHelper.ExecuteSQL(strSql));
            if (count > 0)
            {
                Frame.Global.GlobalFunctions.Alert("删除成功！");
            }
        }
        catch (Exception)
        {

            throw;
        }  
        tvShow();
        DXTreelist.CancelEdit();
        e.Cancel=true;

    }
    #endregion

    #region 判断输入的编号是否符合规范
    //// 判断输入的社区编号是否符合要求
    protected string checkcode(string CommunityID)
    {
        string message = "";
        Regex num = new Regex(@"^[0-9]{6}$");
        if (!num.IsMatch(CommunityID))
        {
            message = "输入的格式不正确！<编号必须为六位数字>";
        }
        else
        {
            message = "true";
        }
        return message;
    }
    //检查输入的城区编码是否正确
    protected string CheckCityCode(string CommunityID)
    {
        //^\d{2}$

        string message = "";
        Regex num = new Regex(@"^[0-9]{2}$");
        //Regex num = new Regex(@"^\d{2}$");
        if (!num.IsMatch(CommunityID))
        {
            message = "输入的格式不正确！<编号必须为两位数字>";
        }
        else
        {
            message = "true";
        }
        return message;
    }
    //检查输入的街道编码是否正确
    protected string CheckStreetCode(string CommunityID)
    {
        string message = "";
        Regex num = new Regex(@"^[0-9]{4}$");
        if (!num.IsMatch(CommunityID))
        {
            message = "输入的格式不正确！<编号必须为四位数字>";
        }
        else
        {
            message = "true";
        }
        return message;
    }
    #endregion 

    #region 清空文本框数据
    //清空城区数据
    private void ClearCity()
    {
        this.txtCityID.Text = "";
        this.txtCityName.Text = "";
    }
    //清空街道数据
    private void ClearStreet()
    {
        this.txtStreetID.Text = "";
        this.txtStreetName.Text = "";
    }
    //清空社区数据
    private void ClearCommunity()
    {
        this.txtCommunityID.Text = "";
        this.txtCommunityName.Text = "";
    }
    #endregion 

    #region 原始
    //选择不同的用户显示不同的社区
    //protected void DXTreelist_CustomCallback(object sender, DevExpress.Web.ASPxTreeList.TreeListCustomCallbackEventArgs e)
    //{
    //    string[] Communities;
    //    string CommunityName = Frame.Global.GlobalSqlHelper.ExcuteSQLScalar("select Communities from Users where ID=" + e.Argument).ToString();
    //    Communities = CommunityName.Split('|');
    //    //清除所有选择
    //    for (int i = 0; i < this.DXTreelist.Nodes.Count; i++)
    //    {
    //        this.DXTreelist.Nodes[i].Selected = false;
    //    }

    //    if (Communities.Length > 0)
    //    {
    //        for (int i = 0; i < Communities.Length; i++)
    //        {
    //            //显示社区信息
    //            if (!Communities[i].Equals(""))
    //            {
    //                TreeListNode selection = this.DXTreelist.FindNodeByKeyValue(Communities[i]);
    //                if (selection != null)
    //                {
    //                    selection.Selected = true;
    //                }
    //            }
    //        }
    //    }

    //}

    //保存用户所选社区
    //protected void ASPxCallbackPanel1_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    //{
    //    //判断是否选择了用户
    //    if (e.Parameter.Equals("null"))
    //    {
    //        throw new Exception("请选择人员！");
    //    }

    //    string Communities = "";
    //    if (this.DXTreelist.GetSelectedNodes().Count > 0)   //查看是否勾选了社区信息
    //    {
    //        List<TreeListNode> selection = this.DXTreelist.GetSelectedNodes();   //获取勾取的社区信息
    //        // 遍历node并连接成字符串
    //        foreach (TreeListNode node in selection)
    //        {
    //            Communities = Communities + node.GetValue("Community_ID") + "|";
    //        }
    //    }


    //    //保存信息
    //    List<SqlParameter> param = new List<SqlParameter>();
    //    param.Add(new SqlParameter("@ID", e.Parameter));
    //    param.Add(new SqlParameter("@Communities", Communities));
    //    Frame.Global.GlobalSqlHelper.ExcuteSQLScalar("update Users set Communities=@Communities where ID=@ID", param.ToArray());
    //}

    #endregion

  
    //添加城区
    protected void btnAddCity_Click(object sender, EventArgs e)
    {
        string message = CheckCityCode(this.txtCityID.Text);
      
        if (string.IsNullOrEmpty(this.txtCityID.Text))
        {
            Frame.Global.GlobalFunctions.Alert("请输入城区编号！");
        }
        else if (string.IsNullOrEmpty(this.txtCityName.Text))
        {
            Frame.Global.GlobalFunctions.Alert("请输入城区名称！");
        }
        else if (!message.Equals("true"))
        {
            Frame.Global.GlobalFunctions.Alert(message);
            ClearCity();
        }
        else
        {
            string CommunityID = this.txtCityID.Text;
            string CommunityName = this.txtCityName.Text;
            string ParentID = "0";
            string strSql = "select count(*) from Community where Community_ID='" + CommunityID + "'or Community_Name='" + CommunityName + "'";
            int Count = Convert.ToInt32(Frame.Global.GlobalSqlHelper.ExcuteSQLScalar(strSql));
            if (Count > 0)
            {
                Frame.Global.GlobalFunctions.Alert("对不起您添加的城区已经存在！");
                ClearCity();
            }
            else
            {
                int counts = Convert.ToInt32(Frame.Global.GlobalSqlHelper.ExecuteSQL("insert into Community values('" + CommunityID + "','" + CommunityName + "','" + ParentID + "')"));
                if (counts > 0)
                {
                    Frame.Global.GlobalFunctions.Alert("添加成功！");
                    ClearCity();
                    tvShow();
                    //this.cmdCity1.SelectCommand = "select * from dbo.Community where Community_ID =  RIGHT('00'+CAST(Community_ID AS VARCHAR(2)),2)";
                    //this.cmdCity.SelectCommand = "select * from dbo.Community where Community_ID =  RIGHT('00'+CAST(Community_ID AS VARCHAR(2)),2)";
                
                }
            }
        }
    }

    //添加街道
    protected void btnStreetAdd_Click(object sender, EventArgs e)
    {  
        string message = CheckCityCode(this.txtStreetID.Text);
        if (Session["city"] == null && this.lblcity.Text.Equals(""))
        { 
          Frame.Global.GlobalFunctions.Alert("请选择所属的城区！");
        }
        if (Session["city"] != null && ParentID.Length == 2)
        {
            this.lblcity.Text = Session["city"].ToString();
        }
        if (Session["cityid"] != null && ParentID.Length == 2)
        {
            this.lblcityid.Text = Session["cityid"].ToString();
        }

        if (this.txtStreetID.Text.Equals(""))
        {
            Frame.Global.GlobalFunctions.Alert("请输入街道编号！");
            if (Session["city"] != null && Session["cityid"] != null)
            {
                this.lblcity.Text = Session["city"].ToString();
                this.lblcityid.Text = Session["cityid"].ToString();
            }
        }
        else if (this.txtStreetName.Text.Equals(""))
        {
            Frame.Global.GlobalFunctions.Alert("请输入街道名称！");
            if (Session["city"] != null && Session["cityid"] != null)
            {
                this.lblcity.Text = Session["city"].ToString();
                this.lblcityid.Text = Session["cityid"].ToString();
            }
        }
        else if (!message.Equals("true"))
        {
            Frame.Global.GlobalFunctions.Alert(message);
            if (Session["city"] != null && Session["cityid"] != null)
            {
                this.lblcity.Text = Session["city"].ToString();
                this.lblcityid.Text = Session["cityid"].ToString();
            }
        }
        else if (ParentID.Equals(""))
        {
            Frame.Global.GlobalFunctions.Alert("对不起请先添加城区");
             if (Session["city"] != null && Session["cityid"] != null)
            {
                this.lblcity.Text = Session["city"].ToString();
                this.lblcityid.Text = Session["cityid"].ToString();
            }
        }
        else
        {
            string streetid = this.lblcityid.Text + this.txtStreetID.Text;
            string strSql = "select count(*) from Community where Community_ID='" + streetid + "'or Community_Name='" + this.txtStreetName.Text + "'";
            int count = Convert.ToInt32(Frame.Global.GlobalSqlHelper.ExcuteSQLScalar(strSql));
            if (count > 0)
            {
                Frame.Global.GlobalFunctions.Alert(" 对不起您添加的街道已经存在！");
                 if (Session["city"] != null && Session["cityid"] != null)
                {
                    this.lblcity.Text = Session["city"].ToString();
                    this.lblcityid.Text = Session["cityid"].ToString();
                }
            }
            else
            {
                int counts = Convert.ToInt32(Frame.Global.GlobalSqlHelper.ExecuteSQL("insert into Community values('" + streetid + "','" + this.txtStreetName.Text + "','" + ParentID + "')"));
                if (counts > 0)
                {
                    Frame.Global.GlobalFunctions.Alert("添加成功！");
                    if (Session["city"] != null && Session["cityid"] != null)
                    {
                        this.lblcity.Text = Session["city"].ToString();
                        this.lblcityid.Text = Session["cityid"].ToString();
                    }
                    ClearStreet();
                    this.lblcity.Text = "";
                    tvShow();
                }
            }
        }
        
    }
  
    //添加社区
    protected void btnOKCommunity_Click(object sender, EventArgs e)
    {
        string message =  CheckCityCode(this.txtCommunityID.Text);

        if (Session["street"] == null && this.lblStreet.Text.Equals("") && this.lblstreetid.Text.Equals(""))
        {
            Frame.Global.GlobalFunctions.Alert("请选择所属的街道！");
        }
        if (Session["street"] != null && ParentID.Length == 4 && Session["streetid"] != null)
        {
            this.lblStreet.Text = Session["street"].ToString();
            this.lblstreetid.Text = Session["streetid"].ToString();
        }
        
        if (this.txtCommunityID.Text.Equals(""))
        {
            Frame.Global.GlobalFunctions.Alert("社区编号不能为空！");
            if (Session["street"] != null && Session["streetid"] !=null)
            {
                this.lblStreet.Text = Session["street"].ToString();
                this.lblstreetid.Text = Session["streetid"].ToString();
            }
        }
        else if (this.txtCommunityName.Text.Equals(""))
        {
            Frame.Global.GlobalFunctions.Alert("社区名称不能为空！");
            if (Session["street"] != null && Session["streetid"] !=null)
            {
                this.lblStreet.Text = Session["street"].ToString();
                this.lblstreetid.Text = Session["streetid"].ToString();
            }
        }
        else if (!message.Equals("true"))
        {
            Frame.Global.GlobalFunctions.Alert(message);
            if (Session["street"] != null && Session["streetid"] !=null)
            {
                this.lblStreet.Text = Session["street"].ToString();
                this.lblstreetid.Text = Session["streetid"].ToString();
            }
        }
        else
        {
            string communityid =this.lblstreetid.Text + this.txtCommunityID.Text;
            string strSql = "select count(*) from Community where Community_ID='" + communityid + "'or Community_Name='" + this.txtCommunityName.Text + "'";
            int count = Convert.ToInt32(Frame.Global.GlobalSqlHelper.ExcuteSQLScalar(strSql));
            if (count > 0)
            {
                Frame.Global.GlobalFunctions.Alert(" 对不起您添加的社区已经存在！");
                if (Session["street"] != null && Session["streetid"] !=null)
                {
                    this.lblStreet.Text = Session["street"].ToString();
                    this.lblstreetid.Text = Session["streetid"].ToString();
                }
            }
            else
            {
                
                int counts = Convert.ToInt32(Frame.Global.GlobalSqlHelper.ExecuteSQL("insert into Community values('" + communityid + "','" + this.txtCommunityName.Text + "','" + ParentID + "')"));
                if (counts > 0)
                {
                    Frame.Global.GlobalFunctions.Alert("添加成功！");
                    if (Session["street"] != null && Session["streetid"] != null)
                    {
                        this.lblStreet.Text = Session["street"].ToString();
                        this.lblstreetid.Text = Session["streetid"].ToString();
                    }
                    ClearCommunity();
                    this.lblStreet.Text = "";
                    tvShow();
                }
            }
        }
    }


    protected void DXTreelist_CustomDataCallback(object sender, TreeListCustomDataCallbackEventArgs e)
    {
        //获取编号
        string key = e.Argument.ToString();
        TreeListNode node = DXTreelist.FindNodeByKeyValue(key);
        //获取上级编号
        //ParentID = node.ParentNode.Key;
        ParentID = key;
        if (ParentID == "")
        {
            ParentID = "0";
        }
        //获取对应的名称
        string nodes = node.GetValue("Community_name").ToString();
        if (nodes != null)
        { 
         e.Result = node.GetValue("Community_Name");
        }
        if (ParentID.Length== 2)
        {
            Session["city"] = e.Result.ToString();
            Session["cityid"] = ParentID.ToString();
        }
        else if (ParentID.Length == 4)
        {
            Session["street"] = e.Result.ToString();
            Session["streetid"] = ParentID.ToString();
        }
    }
}